package com.emovimento.synchronize;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Tray {
  private final BothDirectionsSynchronizingDirectoryWatcher watcher;
  private final TrayIcon trayIcon;

  public Tray(final BothDirectionsSynchronizingDirectoryWatcher watcher) {
    this.watcher = watcher;
    trayIcon = new TrayIcon(getTrayImage(), "starting synchronization...", getTrayPopupMenu());
  }

  public void start() {
    if ( !SystemTray.isSupported()) throw new IllegalStateException("system tray is not supported on this system");

    trayIcon.setToolTip("synchronizing files in background...");
    trayIcon.setImageAutoSize(true);

    try {
      SystemTray.getSystemTray().add(trayIcon);
    } catch (final AWTException e) {
      throw new IllegalStateException("TrayIcon could not be added to system tray.");
    }

  }

  private Image getTrayImage() {
    try {
      return ImageIO.read(ClassLoader.getSystemResource("tray-icon.jpg"));
    } catch (final IOException e1) {
      assert false : "Could not read the tray-icon image";
      return null;
    }
  }

  private PopupMenu getTrayPopupMenu() {
    final PopupMenu popup = new PopupMenu();
    popup.add(getStartStopMenuItem());
    return popup;
  }

  private MenuItem getStartStopMenuItem() {
    final MenuItem exitItem = new MenuItem("Stop");
    exitItem.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent actionEvent) {
        if (exitItem.getLabel().equals("Stop")) {
          watcher.stopWatching();
          exitItem.setLabel("Start");
          return;
        }
        watcher.watchInBackgroundThread();
        exitItem.setLabel("Stop");
        trayIcon.setToolTip("starting synchronization...");
      }
    });
    return exitItem;
  }

  public void setToolTip(final String toolTip) {
    trayIcon.setToolTip(toolTip);
  }

}
